<?php
class Message_Manager extends Model {
	
	private $_current_blogger_id;
	
	function Message_Manager() {
		parent::Model();
		$this->_current_blogger_id = 0;
	}
	
	function SetCurrentBloggerID($current_blogger_id) {
		$this->_current_blogger_id = $current_blogger_id;
	}
	
	function SendPrivateMessage($pm) {
		$parms = array(
			'sender_name' => $pm['sender_name'],
			'to_blogger_id' => $pm['to_blogger_id'],
			'title' => $pm['title'],
			'content' => $pm['content'],
			'sent_time' => $pm['sent_time'],
			'sender_email' => $pm['sender_email'],
			'ip' => $pm['ip'],
			'from_blogger_id' => $pm['from_blogger_id']
		);
		$this->db->insert('nt_messages', $parms);
	}
	
	function DeletePMs($arr_msg_ids) {
		$str_msg_ids = implode(', ', $arr_msg_ids);
		$this->db->query('DELETE FROM `nt_messages` WHERE `id` IN (' . $str_msg_ids . ')');
	}
	
	function DeletePM($pm_id) {
		$this->db->query('DELETE FROM `nt_messages` WHERE `id` = ? AND `to_blogger_id` = ?', array($pm_id, $this->_current_blogger_id));
	}
	
	function GetPMList() {
		$qry = $this->db->query('SELECT `id`, `to_blogger_id`, `sender_name`, `sender_email`, `title`, `sent_time`, `from_blogger_id`, `read` FROM `nt_messages` WHERE `to_blogger_id` = ? ORDER BY `id` DESC', array($this->_current_blogger_id));
		return $qry->result();
	}
	
	function GetUnreadPMNum() {
		$qry = $this->db->query('SELECT COUNT(`id`) AS `unread_num` FROM `nt_messages` WHERE `read` = 0 AND `to_blogger_id` = ?', array($this->_current_blogger_id));
		return $qry->row()->unread_num;
	}
	
	function GetPrivateMessage($pm_id) {
		$qry = $this->db->query('SELECT * FROM `nt_messages` WHERE `id` = ? AND `to_blogger_id` = ?', array($pm_id, $this->_current_blogger_id));
		if($qry->num_rows() < 1) {
			return NULL;
		} else {
			// mark as read
			$this->db->query('UPDATE `nt_messages` SET `read` = 1 WHERE `id` = ?', array($pm_id));
			return $qry->row();
		}
	}
}
?>